package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConst;
import com.atguigu.common.to.SpuBoundsTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.to.es.SkuHasStockVo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;


    @Autowired
    SkuInfoService skuInfoService;


    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrService attrService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }


    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {

        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        //1：保存spu的基本信息   pms_spu_info
        this.saveBaseInfo(spuInfoEntity);

        //2: 保存spu的描述图片   pms_spu_info_desc
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        //3：保存SPU的图片集     pms_spu_images
        List<String> images = spuSaveVo.getImages();

        spuImagesService.saveSpuImages(spuInfoEntity.getId(), images);
        //4：保存SPU的规格参数   pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();

        productAttrValueService.saveBaseAttrs(spuInfoEntity.getId(), baseAttrs);

        //5：保存spu的积分信息 gulimall-sms ==>sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        if (bounds != null) {
            SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
            BeanUtils.copyProperties(bounds, spuBoundsTo);
            spuBoundsTo.setSpuId(spuInfoEntity.getId());
            R r = couponFeignService.saveCouponSpuBounds(spuBoundsTo);
            if (r.getCode() != 0) {
                log.error("远程保存spu积分信息失败");
            }
        }

        //6：保存当前Spu对应的所有Sku信息
        List<Skus> skus = spuSaveVo.getSkus();
        skuInfoService.saveSkuInfo(spuInfoEntity.getId(), spuInfoEntity.getCatalogId(), spuInfoEntity.getBrandId(), skus);

    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((x) -> {
                x.eq("id", key).or().like("spu_name", key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String categoryId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(categoryId)) {
            wrapper.eq("catalog_id", categoryId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);


    }

    @Override
    public void spuUp(long spuId) {

        List<SkuEsModel> skuEsModelList = new ArrayList<>();


        //1：查询当前spuId对应所有的sku的信息,品牌的名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);

        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //TODO 4: 查询当前sku的所有可以用来检索的规格属性
        List<ProductAttrValueEntity> attrList = productAttrValueService.baseAttrListforSpuId(spuId);
        List<Long> collect1 = attrList.stream().map(x -> x.getAttrId()).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.selectSeatchAttrIds(collect1);

        Set<Long> idSet = new HashSet<>(searchAttrIds);

        List<SkuEsModel.Attrs> esAttrs = attrList.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(ite -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(ite, attrs1);
            return attrs1;
        }   ).collect(Collectors.toList());


        Map<Long, Boolean> skuHasStockMap = null;
        try {
//            List<SkuHasStockVo> skushasStock = wareFeignService.getSkushasStock(skuIds);
            R skushasStock = wareFeignService.getSkushasStock(skuIds);
//            skuHasStockMap = skushasStock.
//                    stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
            TypeReference<List<SkuHasStockVo>> skuHasStockVoTypeReference = new TypeReference<List<SkuHasStockVo>>(){};
            skuHasStockMap = skushasStock.getData(skuHasStockVoTypeReference).
                    stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("库存服务查询异常：原因{}", e);
        }

        Map<Long, Boolean> finalSkuHasStockMap = skuHasStockMap;
        List<SkuEsModel> collect = skuInfoEntities.stream().map(sku -> {
            //组装需要上线的数据
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            //hotScore hotStock
            //TODO 1：发送远程调用，库存系统查询是否有库存
            if (finalSkuHasStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                Boolean aBoolean = finalSkuHasStockMap.get(sku.getSkuId());
                skuEsModel.setHasStock(aBoolean);
            }


            //TODO 2: 热度评分，刚上架的商品为0
            skuEsModel.setHotScore(0L);

            //TODO 3:查询品牌与分类的名字
            BrandEntity byId = brandService.getById(sku.getBrandId());
            if (byId != null) {
                skuEsModel.setBrandName(byId.getName());
                skuEsModel.setBrandImg(byId.getLogo());
            }

            CategoryEntity byId1 = categoryService.getById(sku.getCatalogId());
            if (byId1 != null) {
                skuEsModel.setCatalogName(byId1.getName());
            }
            //设置检索属性
            skuEsModel.setAttrs(esAttrs);

            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 5: 发送给ES进行保存
        R r = searchFeignService.productStatusUp(collect);
        if (r.getCode() == 0) {
            //远程调用成功
            //TODO 6:修改当前spu的状态
            this.baseMapper.updateSpuStatus(spuId, ProductConst.StatusEnum.SPU_UP.getCode());
        } else {
            //远程调用失败
            //重复调用的问题，接口的幂等性，重试机制
        }


    }

    @Override
    public void fetgnTest() {
        R r = couponFeignService.feignTest();
        System.out.println("远程接口调用成功");

    }


    public void saveBaseInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

}
